#include "project.h"

void Lcd::drawChar16x16(char c, int x, int y, uint32_t color) {
    const unsigned char* bitmap = FontManager::getInstance().getCharBitmap(c);
    if (!bitmap) {
        std::cerr << "⚠️ 字符 '" << c << "' 无点阵数据" << std::endl;
        return;
    }

    for (int row = 0; row < 16; ++row) {
        unsigned char line = bitmap[row];  // 前8列的数据

        // 绘制左半部分（列 0~7）
        for (int col = 0; col < 8; ++col) {
            if (line & (0x80 >> col)) {
                int px = x + col;
                int py = y + row;
                if (px >= 0 && px < lcd_width && py >= 0 && py < lcd_height) {
                    size_t idx = (size_t)py * lcd_width + px;
                    mmap_start[idx] = color;
                    // 🔍 调试：打印绘制的点
                    //std::cout << ".debugLine[" << row << "] 绘制点 (" << px << "," << py << ") 字符 '" << c << "'" << std::endl;
                }
            }
        }

        line = bitmap[row + 16];  // 后8列的数据

        // 绘制右半部分（列 8~15）
        for (int col = 0; col < 8; ++col) {
            if (line & (0x80 >> col)) {
                int px = x + col + 8;
                int py = y + row;
                if (px >= 0 && px < lcd_width && py >= 0 && py < lcd_height) {
                    size_t idx = (size_t)py * lcd_width + px;
                    mmap_start[idx] = color;
                    // 🔍 调试：打印绘制的点
                    //std::cout << "drawRight[" << row << "] 绘制点 (" << px << "," << py << ") 字符 '" << c << "'" << std::endl;
                }
            }
        }
    }
}

void Lcd::drawString16x16(const std::string& str, int x, int y, uint32_t color) {
    int cur_x = x;
    for (char c : str) {
        drawChar16x16(c, cur_x, y, color);
        cur_x += 16; // 每个字符宽 16px
        if (cur_x >= lcd_width) break;
    }
}

void Lcd::displayTime() {
    std::string time_str = TimeManager::getInstance().getCurrentTime(); // "HH:MM:SS"

    std::cout << "[DEBUG] 当前时间字符串: \"" << time_str << "\"" << std::endl;

    int char_width = 16;
    int char_height = 16;
    int text_width = time_str.length() * char_width;

    int margin = 10;
    int x = lcd_width - text_width - margin;
    int y = lcd_height - char_height - margin;

    // 可选：画一个黑色背景块提高可读性
    for (int py = y; py < y + char_height; ++py) {
        for (int px = x; px < x + text_width; ++px) {
            size_t idx = (size_t)py * this->lcd_width + px;
            if (idx < (size_t)this->lcd_width * this->lcd_height) {
                this->mmap_start[idx] = 0x000000; // 黑色
            }
        }
    }

    drawString16x16(time_str, x, y, 0xFFFFFF); // 白色文字

    // 在 displayTime() 结束时调用
    if (msync(mmap_start, lcd_width * lcd_height * sizeof(uint32_t), MS_SYNC) == -1) {
        perror("msync");
        // 处理错误...
    }
}